<?php
/**
 * Niushop商城系统 - 团队十年电商经验汇集巨献!
 * =========================================================
 * Copy right 2019-2029 上海牛之云网络科技有限公司, 保留所有权利。
 * ----------------------------------------------
 * 官方网址: https://www.niushop.com
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用。
 * 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
 * =========================================================
 */

namespace app\model\system;

use think\facade\Session;
use app\model\BaseModel;
use think\facade\Cache;

/**
 * 管理员模型
 */
class SysUser extends BaseModel
{

	/*******************************************************************用户 编辑查询 start*****************************************************/
	
	/**
	 * 添加用户
	 * @param $data
	 */
	public function addUser($data)
	{
		//判断 用户名 是否存在
		$user_info = model('sys_user')->getInfo([ [ 'username', "=", $data["username"] ] ]);
		if (!empty($user_info)) {
			return $this->error('', '账号已存在');
		}
		
		$data["password"] = data_md5($data["password"]);
		$data["create_time"] = time();
		$auth = Cache::get("niushop_cert");
		if (!empty($auth)) {
			if ($auth['user_num'] != 0) {
				//表示非无限
				$user_count = model('sys_user')->getCount();
				if ($user_count >= $auth['user_num']) {
					return $this->error([], '当前授权已经不允许创建用户');
				}
			}
		}
		
		$result = model("sys_user")->add($data);
		if ($result === false) {
			return $this->error('', 'UNKNOW_ERROR');
		}
		return $this->success($result);
	}
	
	/**
	 * 编辑用户
	 * @param $data
	 * @param $condition
	 */
	public function editUser($data, $condition)
	{
		
		$res = model("sys_user")->update($data, $condition);
		if ($res === false) {
			return $this->error('', 'UNKNOW_ERROR');
		}
		return $this->success($res);
	}
	
	/**
	 * 编辑用户状态
	 * @param $status
	 * @param $condition
	 */
	public function modifyUserStatus($status, $condition)
	{
		$check_condition = array_column($condition, 2, 0);
		$site_id = isset($check_condition['site_id']) ? $check_condition['site_id'] : '';
		$app_module = isset($check_condition['app_module']) ? $check_condition['app_module'] : '';
		if ($site_id === '') {
			return $this->error('', 'REQUEST_SITE_ID');
		}
		if ($app_module === '') {
			return $this->error('', 'REQUEST_APP_MODULE');
		}
		$data = array(
			"status" => $status,
			"update_time" => time()
		);
		$res = model('user')->update($data, $condition);
		if ($res === false) {
			return $this->error('', 'UNKNOW_ERROR');
		}
		return $this->success($res);
	}
	
	/**
	 * 重置密码
	 * @param $password
	 * @param $condition
	 * @return array|\multitype
	 */
	public function modifyUserPassword($password, $condition)
	{
		$password = data_md5($password);
		$check_condition = array_column($condition, 2, 0);
		$sys_uid = $check_condition['sys_uid'];
		if (empty($sys_uid)) {
			return $this->error('', '参数错误');
		}
		$res = model('sys_user')->update([ 'password' => $password ], $condition);
		//同时修改user表的
		model('user')->update([ 'password' => $password ], [ [ 'sys_uid', '=', $sys_uid ] ]);
		if ($res === false) {
			return $this->error('', 'RESULT_ERROR');
		}
		return $this->success($res);
	}
	
	/**
	 * 系统用户修改密码
	 *
	 * @param unknown $uid
	 * @param unknown $old_password
	 * @param unknown $new_password
	 */
	public function modifyAdminUserPassword($sys_uid, $old_password, $new_password)
	{
		$condition = array(
			'sys_uid' => $sys_uid,
			'password' => data_md5($old_password)
		);
		$res = model('sys_user')->getInfo($condition, "sys_uid");
		if (!empty($res['sys_uid'])) {
			$data = array(
				'password' => data_md5($new_password)
			);
			$res = model('sys_user')->update($data, [
				'sys_uid' => $sys_uid
			]);
			//同时修改user表中的密码
			model('user')->update($data, [
				'sys_uid' => $sys_uid
			]);
			
			return $this->success($res, 'SUCCESS');
		} else {
			return $this->error('', 'PASSWORD_ERROR');
		}
	}
	
	/**
	 * 删除用户
	 * @param array $condition
	 * @return multitype:string mixed
	 */
	public function deleteUser($condition)
	{
		
		$check_condition = array_column($condition, 2, 0);
		$sys_uid = $check_condition['sys_uid'];
		$site_count = model('site')->getCount([ [ 'sys_uid', '=', $sys_uid ] ]);
		if ($site_count > 0) {
			return $this->error('', '该系统用户下有站点，不可删除！');
		}
		$res = model('sys_user')->delete($condition);
		if ($res === false) {
			return $this->error('', 'UNKNOW_ERROR');
		}
		
            //todo  删除用户下的所有站点 可能需要完善
//        $site_model = new Site();
//        $site_result = $site_model->deleteSite([['sys_uid', '=', $sys_uid]]);
//        if($site_result['code'] < 0){
//            return $site_result;
//        }

		return $this->success($res);
	}
	
	
	/**
	 * 获取用户信息
	 * @param $condition
	 * @param string $field
	 * @return \multitype
	 */
	public function getUserInfo($condition, $field = "*")
	{
		$info = model('sys_user')->getInfo($condition, $field);
		return $this->success($info);
	}
	
	/**
	 * 获取用户列表
	 * @param array $condition
	 * @param string $field
	 * @param string $order
	 * @param string $limit
	 * @return multitype:string mixed
	 */
	public function getUserList($condition = [], $field = 'sys_uid, username, mobile, password, create_time, update_time, status, login_time, login_ip, is_admin', $order = '', $limit = null)
	{
		$list = model('sys_user')->getList($condition, $field, $order, '', '', '', $limit);
		return $this->success($list);
	}
	
	
	/**
	 * 获取会员分页列表
	 * @param array $condition
	 * @param number $page
	 * @param string $page_size
	 * @param string $order
	 * @param string $field
	 * @return multitype:string mixed
	 */
	public function getUserPageList($condition = [], $page = 1, $page_size = PAGE_LIST_ROWS, $order = '', $field = 'sys_uid, username, mobile, password, create_time, update_time, status, login_time, login_ip, is_admin, created_site_num')
	{
		$list = model('sys_user')->pageList($condition, $field, $order, $page, $page_size);
		return $this->success($list);
	}
	
	/*******************************************************************用户注册登录 start*****************************************************/
	
	/**
	 * 用户登录
	 * @param unknown $mobile
	 * @param unknown $password
	 */
	public function login($username, $password, $app_module)
	{
		$time = time();
		// 验证参数 预留
		if ($app_module == 'admin') {
			$condition = [
				[ 'username', '=', $username ],
				[ 'is_admin', '=', 1 ]
			];
		} else {
			$condition = [
				[ 'username', '=', $username ]
			];
		}
		$sys_user_info = model('sys_user')->getInfo($condition);
		if (empty($sys_user_info)) {
			return $this->error('', 'USER_LOGIN_ERROR');
		} else if (data_md5($password) !== $sys_user_info['password']) {
			return $this->error([], 'PASSWORD_ERROR');
		} else if ($sys_user_info['status'] !== 1) {
			return $this->error([], 'USER_IS_LOCKED');
		}
		$auth = Cache::get("niushop_cert");
		if ($auth['user_num'] != 0) {
			//表示非无限
			$user_count = model('sys_user')->getCount();
			if ($user_count > ($auth['user_num'] + 1)) {
				return $this->error([], '授权账户数目是' . ($auth['user_num'] + 1) . '，请删除多余客户');
			}
		}
		// 记录登录SESSION
		$auth = array(
			'sys_uid' => $sys_user_info['sys_uid'],
			'username' => $sys_user_info['username'],
			'mobile' => $sys_user_info['mobile'],
			'is_admin' => $sys_user_info['is_admin'],
			'create_time' => $sys_user_info['create_time'],
			'status' => $sys_user_info['status'],
			'login_time' => $time,
			'login_ip' => request()->ip()
		);
		
		//更新登录记录
		$data = [
			'login_time' => time(),
			'login_ip' => request()->ip(),
		];
		model('sys_user')->update($data, [ [ 'sys_uid', '=', $sys_user_info['sys_uid'] ] ]);
		//填写日志
		Session::set($app_module . '.' . 'sys_uid', $sys_user_info['sys_uid']);
		Session::set($app_module . '.' . 'sys_user_info', $auth);
		return $this->success();
	}
	
	/**
	 * 获取当前登录uid
	 * @param unknown $app_module
	 */
	public function sys_uid($app_module)
	{
		return Session::get($app_module . '.' . 'sys_uid');
	}
	
	/**
	 * 获取当前登录管理员信息
	 * @param unknown $app_module
	 */
	public function sysUserInfo($app_module)
	{
		return Session::get($app_module . '.' . 'sys_user_info');
	}
	
	/**
	 * 清除登录信息
	 */
	public function clearLogin($app_module)
	{
		Session::delete($app_module);
	}
	/*******************************************************************用户注册登录 end*****************************************************/
	
	
	/*******************************************************************用户数据统计 start*****************************************************/
	
	/**
	 * 获取用户数
	 * @return int
	 */
	public function getSysuserCount($condition = [])
	{
		$res = model('sys_user')->getCount($condition);
		return $res;
	}
	
	/**
	 *某个字段统计
	 * @param array $condition
	 * @param $field
	 * @return array
	 */
	public function getSysuserSum($condition = [], $field)
	{
		$res = model('sys_user')->getSum($condition, $field);
		return $this->success($res);
	}
	/*******************************************************************用户数据统计 end*****************************************************/
	
	

}